;
(function() {
	var config = require("../../core/_include/config");
	var ResponObj = require("../_include/responObj");
	var qiniu = require("./qiniu");
	var fs = require("fs");
	var path = require("path");
	var multipart = require('connect-multiparty');
	var multipartMiddleware = multipart();

	var result_cache = {};

	//查看缓存文件夹是否存在
	var temp_path = fs.existsSync(__dirname + "/../_temp")
	if (!temp_path) { //创建缓存文件夹
		fs.mkdirSync(temp_path);
	};
	module.exports = {
		prefix: "/file",
		_init: function() {

		},
		post: {
			"/upload/image": [multipartMiddleware, function() {
				//客户端用iframe提交的话由于安全性，是无法获取到JSON返回值。
				//因此，将返回值通过客户端提供的HASH存储在一个临时对象中
				//下次请求通过get方法来获取回调
				var self = this;
				var result_hash = self.request.query.cb_hash;
				var files = self.request.files;
				var result = {};

				// console.log(result_hash,files);
				var field_keys = Object.keys(files);
				if (!field_keys.length) {
					var result = ResponObj("error", "参数错误");
					if (result_hash) {
						this.body = "upload error!";
						result_cache[result_hash] = result
					} else {
						this.body = "参数错误";
					}
				}
				field_keys.forEach(function(field_key) {
					! function(field_key) {
						var file = files[field_key];
						//文件格式非图片文件，报错
						console.log(file.headers["content-type"], file.path);
						if (file.headers["content-type"].indexOf("image") === -1) {
							fs.unlink(file.path);
							throwCusError("文件格式错误")
						}
						//从缓存区上传文件
						console.log("upload file to qiniu:", file.path);
						qiniu.upload(file.path, function(error, ret) {
							//上传完成后，删除缓存文件
							fs.unlink(file.path);
							if (error) {
								console.log("error", error);
								if (result_hash) {
									result_cache[result_hash] = ResponObj("error", "上传权限有误");
									self.body = "upload error!"
								} else {
									self.body = "上传权限有误";
								}
								return;
							}
							// console.log(ret);
							result[field_key] = ret
							if (result_hash) {
								result_cache[result_hash] = ResponObj("json", result);
								result.__ti__ = setTimeout(function() {
									console.log("删除", result_hash);
									delete result_cache[result_hash];
								}, config.uploadCallbackDateTimeOut);
								self.body = "upload success!"
							} else {
								self.body = ret;
							}
						});
					}(field_key);
				});
			}],
			"/upload/image/base64": function() {
				var self = this;
				var body = self.request.body;
				var base64_data = body.img_base64;
				if (!base64_data) {
					throwCusError("参数错误")
				}
				var matches = base64_data.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);

				if (matches.length !== 3) {
					return new Error('Invalid input string');
				}
				var file_type = matches[1];
				if (file_type.indexOf("image\/") !== 0) {
					throwCusError("上传的文件不是图片类型")
				}
				var file_buffer = new Buffer(matches[2], 'base64');

				qiniu.uploadBuff(file_buffer, function(err, ret) {
					if (err) {
						console.dir(err);
						throwCusError("QINIU Error:(" + err.code + ")" + err.error)
						return;
					}
					self.body = ResponObj("json", ret);
				});
			},
			//多图上传
			"/upload/imgs/base64": function() {
				var self = this;
				var body = self.request.body;
				var imgs = body.imgs;
				if (!(imgs instanceof Array)) {
					throwCusError("参数错误")
				}
				var result = [];
				var yield_num = imgs.length;
				imgs.forEach(function(base64_data, index) {
					var matches = base64_data.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
					if (matches.length !== 3) {
						throwCusError("上传数据出错")
					}
					var file_type = matches[1];
					if (file_type.indexOf("image\/") !== 0) {
						throwCusError("上传的文件不是图片类型")
					}
					var file_buffer = new Buffer(matches[2], 'base64');

					qiniu.uploadBuff(file_buffer, function(err, ret) {
						if (err) {
							console.dir(err);
							throwCusError("QINIU Error:(" + err.code + ")" + err.error)
							return;
						}
						result[index] = ret;
						yield_num -= 1;
						if (!yield_num) {//如果所有图片处理完成，返回数据
							self.body = ResponObj("json", result);
						}
					});
				});
			}
		},
		get: {
			"/getcallback/:result_hash": function() {
				var result_hash = this.params.result_hash;
				// console.log(result_cache);
				var result = result_cache[result_hash];
				if (result) {
					// //取一次就可以直接删除了
					// clearTimeout(result.__ti__);
					// delete result_cache[result_hash];
					delete result.__ti__;
					this.body = result;
				} else {
					throw "上传请求超时";
				}
			}
		}
	}
}());